<script>
import { mapState, mapActions } from 'pinia'
import { useProductStore } from '../stores/04.getters(选项式)'
import { useTaskStore } from '../stores/03.state(选项式)'

export default {
  data() {
    const productStore = useProductStore()
    
    return {
      // 库存阈值
      stockThreshold: 10,
      
      // 新产品表单
      newProduct: {
        name: '',
        price: 0,
        category: '',
        stock: 1
      },
      
      // 价格范围
      minPrice: productStore.priceRange.min,
      maxPrice: productStore.priceRange.max
    }
  },
  computed: {
    // 获取store实例
    productStore() {
      return useProductStore()
    },
    taskStore() {
      return useTaskStore()
    }
  },
  methods: {
    // 添加新产品
    addProduct() {
      if (this.newProduct.name && this.newProduct.price > 0 && this.newProduct.category) {
        this.productStore.addProduct({
          name: this.newProduct.name,
          price: Number(this.newProduct.price),
          category: this.newProduct.category,
          stock: Number(this.newProduct.stock)
        })
        // 重置表单
        this.newProduct = {
          name: '',
          price: 0,
          category: '',
          stock: 1
        }
      }
    },
    
    // 更新价格范围
    updatePriceRange() {
      this.productStore.setPriceRange(Number(this.minPrice), Number(this.maxPrice))
    },
    
    // 重置价格范围
    resetPriceRange() {
      const { min, max } = this.productStore.priceStats
      this.minPrice = min
      this.maxPrice = max
      this.productStore.setPriceRange(min, max)
    }
  }
}
</script>

<template>
  <div class="tutorial-container">
    <header>
      <h1>04.getters(选项式)</h1>
      <p class="subtitle">学习如何在选项式API中定义和使用getters</p>
      
      <nav class="tutorial-nav">
        <router-link to="/01" class="nav-link">01.认识pinia</router-link>
        <router-link to="/02" class="nav-link">02.定义store(选项式)</router-link>
        <router-link to="/03" class="nav-link">03.state(选项式)</router-link>
        <router-link to="/04" class="nav-link">04.getters(选项式)</router-link>
      </nav>
    </header>

    <main>
      <section class="intro">
        <h2>什么是 Getters?</h2>
        <p>Getters 相当于 store 的计算属性。它们可以用来过滤或计算派生状态，并且会缓存结果，只有当依赖的状态发生变化时才会重新计算。</p>
        
        <div class="code-example">
          <pre><code>// 定义一个带有getters的store
export const useStore = defineStore('storeId', {
  state: () => ({
    count: 0,
    users: []
  }),
  getters: {
    // 基本getter
    doubleCount(state) {
      return state.count * 2
    },
    // 使用this访问其他getter
    quadrupleCount() {
      return this.doubleCount * 2
    },
    // 返回一个函数的getter (可接收参数)
    getUserById: (state) => (userId) => {
      return state.users.find(user => user.id === userId)
    }
  }
})</code></pre>
        </div>
      </section>

      <div class="demo-section">
        <div class="products-section">
          <h2>产品管理示例</h2>
          
          <!-- 产品过滤器 -->
          <div class="card">
            <h3>产品过滤器</h3>
            
            <div class="filter-section">
              <div class="filter-group">
                <h4>分类</h4>
                <div class="category-filters">
                  <button 
                    @click="productStore.resetCategoryFilter()" 
                    :class="{ active: !productStore.selectedCategory }"
                  >
                    全部
                  </button>
                  <button 
                    v-for="category in productStore.categories" 
                    :key="category"
                    @click="productStore.setCategory(category)"
                    :class="{ active: productStore.selectedCategory === category }"
                  >
                    {{ category }}
                  </button>
                </div>
              </div>
              
              <div class="filter-group">
                <h4>价格范围</h4>
                <div class="price-range">
                  <div class="range-inputs">
                    <div class="input-group">
                      <label>最低价格</label>
                      <input v-model="minPrice" type="number" min="0" />
                    </div>
                    <div class="input-group">
                      <label>最高价格</label>
                      <input v-model="maxPrice" type="number" min="0" />
                    </div>
                  </div>
                  <div class="range-actions">
                    <button @click="updatePriceRange()">应用</button>
                    <button @click="resetPriceRange()" class="secondary-button">重置</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 产品列表 -->
          <div class="card">
            <div class="card-header">
              <h3>产品列表</h3>
              <div class="stats">
                <span>显示 {{ productStore.filteredProductCount }} 个产品</span>
                <span>平均价格: ¥{{ productStore.averagePrice }}</span>
              </div>
            </div>
            
            <table class="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>产品名称</th>
                  <th>分类</th>
                  <th>价格</th>
                  <th>库存</th>
                  <th>总价值</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="product in productStore.filteredProducts" :key="product.id">
                  <td>{{ product.id }}</td>
                  <td>{{ product.name }}</td>
                  <td>{{ product.category }}</td>
                  <td>¥{{ product.price }}</td>
                  <td :class="{ 'low-stock': product.stock < stockThreshold }">
                    {{ product.stock }}
                  </td>
                  <td>¥{{ product.price * product.stock }}</td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="5">总价值:</td>
                  <td>¥{{ productStore.totalValue }}</td>
                </tr>
              </tfoot>
            </table>
          </div>
          
          <!-- 添加新产品 -->
          <div class="card">
            <h3>添加新产品</h3>
            <div class="form-group">
              <label>产品名称:</label>
              <input v-model="newProduct.name" placeholder="输入产品名称" />
            </div>
            <div class="form-group">
              <label>分类:</label>
              <input v-model="newProduct.category" placeholder="输入分类" />
            </div>
            <div class="form-group">
              <label>价格:</label>
              <input v-model.number="newProduct.price" type="number" min="0" />
            </div>
            <div class="form-group">
              <label>库存:</label>
              <input v-model.number="newProduct.stock" type="number" min="0" />
            </div>
            <button @click="addProduct">添加产品</button>
          </div>
        </div>
        
        <div class="info-section">
          <h2>Getters 示例</h2>
          
          <!-- 库存不足产品 -->
          <div class="card">
            <h3>库存不足产品</h3>
            <div class="threshold-control">
              <label>库存阈值:</label>
              <input v-model.number="stockThreshold" type="number" min="1" max="20" />
            </div>
            
            <div v-if="productStore.lowStockProducts(stockThreshold).length === 0" class="empty-message">
              没有库存低于 {{ stockThreshold }} 的产品
            </div>
            
            <ul v-else class="low-stock-list">
              <li v-for="product in productStore.lowStockProducts(stockThreshold)" :key="product.id">
                <span class="product-name">{{ product.name }}</span>
                <span class="stock-badge">库存: {{ product.stock }}</span>
              </li>
            </ul>
          </div>
          
          <!-- 价格统计 -->
          <div class="card">
            <h3>价格统计</h3>
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-label">最低价格</div>
                <div class="stat-value">¥{{ productStore.priceStats.min }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">最高价格</div>
                <div class="stat-value">¥{{ productStore.priceStats.max }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">平均价格</div>
                <div class="stat-value">¥{{ productStore.averagePrice }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">总价值</div>
                <div class="stat-value">¥{{ productStore.totalValue }}</div>
              </div>
            </div>
          </div>
          
          <!-- 任务进度 -->
          <div class="card">
            <h3>任务进度 (跨Store Getter)</h3>
            <div class="task-progress">
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="{ width: `${productStore.taskStats.progress}%` }"
                ></div>
              </div>
              <div class="progress-text">
                {{ productStore.taskStats.progress }}% 完成
              </div>
            </div>
            
            <div class="task-stats">
              <div class="stat-item">
                <div class="stat-label">总任务</div>
                <div class="stat-value">{{ productStore.taskStats.total }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">已完成</div>
                <div class="stat-value">{{ productStore.taskStats.completed }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">未完成</div>
                <div class="stat-value">{{ productStore.taskStats.active }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <section class="code-explanation">
        <h2>Getters 的核心概念</h2>
        
        <div class="explanation-block">
          <h3>1. 基本的 Getter</h3>
          <p>最简单的getter接收state作为第一个参数：</p>
          <pre><code>getters: {
  doubleCount(state) {
    return state.count * 2
  }
}</code></pre>
        </div>
        
        <div class="explanation-block">
          <h3>2. 访问其他 Getter</h3>
          <p>getter可以通过this访问其他getter：</p>
          <pre><code>getters: {
  doubleCount(state) {
    return state.count * 2
  },
  quadrupleCount() {
    // 通过this访问其他getter
    return this.doubleCount * 2
  }
}</code></pre>
        </div>
        
        <div class="explanation-block">
          <h3>3. 向 Getter 传递参数</h3>
          <p>getter本身不能接收参数，但可以返回一个函数来接收参数：</p>
          <pre><code>getters: {
  getUserById: (state) => (userId) => {
    return state.users.find(user => user.id === userId)
  }
}

// 使用方式
const user = store.getUserById(2)</code></pre>
        </div>
        
        <div class="explanation-block">
          <h3>4. 访问其他 Store 的 Getter</h3>
          <p>在一个store中可以导入并使用另一个store：</p>
          <pre><code>import { useUserStore } from './user'

export const useCartStore = defineStore('cart', {
  getters: {
    userCartItems() {
      const userStore = useUserStore()
      return this.items.filter(item => 
        item.userId === userStore.currentUserId
      )
    }
  }
})</code></pre>
        </div>
      </section>
    </main>
  </div>
</template>

<style scoped>
.tutorial-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
    Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
}

header {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  margin-bottom: 2rem;
}

h1 {
  font-size: 2.5rem;
  color: #42b883;
  margin-bottom: 0.5rem;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
}

h2 {
  font-size: 1.8rem;
  color: #2c3e50;
  margin-top: 2rem;
  margin-bottom: 1rem;
  border-bottom: 2px solid #eee;
  padding-bottom: 0.5rem;
}

h3 {
  font-size: 1.4rem;
  color: #2c3e50;
  margin-top: 1.5rem;
  margin-bottom: 0.5rem;
}

h4 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin-top: 1rem;
  margin-bottom: 0.5rem;
}

.tutorial-nav {
  display: flex;
  justify-content: center;
  margin-top: 1.5rem;
  gap: 1rem;
  flex-wrap: wrap;
}

.nav-link {
  padding: 0.5rem 1rem;
  background-color: #f0f0f0;
  border-radius: 4px;
  color: #2c3e50;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.nav-link:hover {
  background-color: #e0e0e0;
}

.nav-link.router-link-active {
  background-color: #42b883;
  color: white;
}

.code-example {
  background-color: #2c3e50;
  color: #fff;
  padding: 1rem;
  border-radius: 8px;
  margin: 1rem 0;
  overflow-x: auto;
}

pre {
  margin: 0;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}

.demo-section {
  display: grid;
  grid-template-columns: 3fr 2fr;
  gap: 2rem;
  margin: 2rem 0;
}

@media (max-width: 1024px) {
  .demo-section {
    grid-template-columns: 1fr;
  }
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.card-header h3 {
  margin: 0;
}

.stats {
  display: flex;
  gap: 1rem;
  color: #666;
  font-size: 0.9rem;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.filter-group {
  margin-bottom: 1rem;
}

.category-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.category-filters button {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  background-color: #f0f0f0;
  color: #2c3e50;
}

.category-filters button.active {
  background-color: #42b883;
  color: white;
}

.price-range {
  margin-top: 0.5rem;
}

.range-inputs {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.input-group {
  flex: 1;
}

.input-group label {
  display: block;
  margin-bottom: 0.25rem;
  font-size: 0.875rem;
  color: #666;
}

.range-actions {
  display: flex;
  gap: 0.5rem;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin: 1rem 0;
}

.data-table th,
.data-table td {
  padding: 0.75rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f8f8;
  font-weight: 600;
}

.data-table tfoot td {
  font-weight: bold;
}

.low-stock {
  color: #e53935;
  font-weight: bold;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.threshold-control {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.threshold-control input {
  width: 80px;
}

.empty-message {
  padding: 1rem;
  text-align: center;
  color: #666;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.low-stock-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.low-stock-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  border-bottom: 1px solid #eee;
}

.stock-badge {
  background-color: #ffebee;
  color: #e53935;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

.stat-item {
  background-color: #f8f8f8;
  padding: 1rem;
  border-radius: 4px;
  text-align: center;
}

.stat-label {
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 0.5rem;
}

.stat-value {
  font-size: 1.25rem;
  font-weight: bold;
  color: #2c3e50;
}

.task-progress {
  margin-bottom: 1.5rem;
}

.progress-bar {
  height: 10px;
  background-color: #eee;
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  height: 100%;
  background-color: #42b883;
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  font-size: 0.875rem;
  color: #666;
}

.task-stats {
  display: flex;
  justify-content: space-between;
}

.task-stats .stat-item {
  flex: 1;
}

.explanation-block {
  margin-bottom: 2rem;
}

.explanation-block pre {
  background-color: #f8f8f8;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
}

input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  width: 100%;
}

button {
  background-color: #42b883;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #33a06f;
}

.secondary-button {
  background-color: #2c3e50;
}

.secondary-button:hover {
  background-color: #1e2a38;
}
</style>
